package com.jiang.booksystem.manager;

import com.jiang.booksystem.core.ApiResponse;
import com.jiang.booksystem.dao.entity.Book;
import com.jiang.booksystem.dao.entity.UserBookBorrow;
import com.jiang.booksystem.dao.entity.dos.UserBookBorrowAggre;
import com.jiang.booksystem.dao.mapper.BookMapper;
import com.jiang.booksystem.dao.mapper.UserBookBorrowMapper;
import com.jiang.booksystem.exception.ServiceException;
import com.jiang.booksystem.exception.ValidateException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import java.util.Date;
import java.util.List;

@Service
public class UserBookBorrowManager {
    @Autowired
    private UserBookBorrowMapper userBookBorrowMapper;
    @Autowired
    private BookMapper bookMapper;
    @Autowired
    private BookManager bookManager;
    @Autowired
    private PlatformTransactionManager tm;

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    public List<UserBookBorrowAggre> search(String bookName) {
        return userBookBorrowMapper.search(bookName);
    }


    public void applyBorrow(int userId, int bookId) {
        // 1. 判断用户是否已经存在正在申请中的借书记录 -》 借阅申请正在处理中
        // 2. 判断用户是否已经借阅当前书籍，（尚未归还）-》该书本已经被你给借阅

        // (1) 一次性取出该用户这本书的所有借阅记录，从记录中验证逻辑1和2
        // (2) 逻辑1和2分别调用sql语句判断

        List<UserBookBorrow> borrows = userBookBorrowMapper.listByUserIdAndBookId(userId, bookId);

        if (borrows != null) {
            for (UserBookBorrow borrow : borrows) {
                if (borrow.getStatus() == 0) {
                    throw new ServiceException("借阅申请正在处理中");
                }
                if (borrow.getStatus() == 1) {
                    throw new ServiceException("该书本已经被你给借阅");
                }
            }
// jdk1.8 支持的语法 Lambda 表达式
//            if (borrows.stream().anyMatch(x -> x.getStatus() == 0)) {
//                throw new ServiceException("借阅申请正在处理中");
//            }

        }

        UserBookBorrow borrow = new UserBookBorrow();
        borrow.setUserId(userId);
        borrow.setBookId(bookId);
        borrow.setStatus(0);
        borrow.setCreateTime(new Date());
        userBookBorrowMapper.insert(borrow);
    }

    public UserBookBorrow getByUserId(int id){
        UserBookBorrow userBookBorrow=userBookBorrowMapper.getByUserId(id);
        return userBookBorrow;
    }

    public void  audit(int id, int status) {

        UserBookBorrow userBookBorrow = userBookBorrowMapper.getById(id);
        logger.info("userBookBorrow:{}", userBookBorrow);


        if (userBookBorrow == null) {
            throw new ServiceException("找不到申请记录");
        }
//        if (userBookBorrow.getStatus() != 0) {
//            throw new ServiceException("只有申请中的才可以审核");
//        }

        Book book = null;
        //修改书本审核   0申请中，1已借阅，2拒绝借阅，3已归还
        if (status == 1) {
            int bookId = userBookBorrow.getBookId();
            book = bookMapper.getById(bookId);
            if (book == null) {
                throw new ServiceException("找不到书本");
            }
        }

        // 事务
        TransactionStatus ts = null;
        try {
            ts = tm.getTransaction(new DefaultTransactionDefinition());

            //修改审核
            userBookBorrow.setStatus(status);
            userBookBorrowMapper.status(userBookBorrow);
            if (book != null) {
                bookManager.updateStock(book.getName(), book.getStock() - 1);
            }

            tm.commit(ts);
        } catch (Exception e) {
            if (ts != null) {
                tm.rollback(ts);
            }
            throw new ServiceException("审核操作失败, 原因：" + e.getMessage());
        }

    }
}
